const router = require('koa-router')();  //注意：引入的方式
const db = require('../utils/database.js')


router.prefix('/classify')

router.get('/', ctx => {
    ctx.body = "classify--index";
})

// 查询 分页 搜索 排序
router.get('/list', async ctx => {
    const { order, by, page = 0, pageSize = 20, query } = ctx.request.query // request可省略
    let sort = {}, where = {}
    if (by) {
        sort[by] = order // by是条件 order是-1或1
    }
    if (query) {
        where.name = { $regex: new RegExp(query) }
    }
    //总条数
    const total = await db.total('classify', where)
    const data = await db.find('classify', { where, sort, skip: page * pageSize, limit: pageSize })
    ctx.body = { success: true, code: 20000, message: "数据查询成功", data, total }
})

router.get('/classifyname', async ctx => {
    //总条数
    const datas = await db.find('classify', { name:1})
    ctx.body = { success: true, code: 20000, message: "数据查询成功", datas }
})

// 新增
router.post('/save', async ctx => {
    const { name, sort, status } = ctx.request.body;
    const data = await db.insert('classify', { name, sort: (sort * 1), status, time: Date.now() })
    ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
})

// 修改
router.post('/modify', async ctx => {
    const { name, _id, sort, status } = ctx.request.body
    const data = await db.update('classify', { _id }, { name, sort: (sort * 1), status, time: Date.now() })
    ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
    const { _id } = ctx.request.query
    const data = await db.delete('classify', { _id })
    ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})


module.exports = router
